1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.google.common.collect;
18
19 import static com.google.common.base.Preconditions.checkNotNull;
20
21 import java.io.Serializable;
22 import java.util.AbstractCollection;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.Iterator;
26
27 import javax.annotation.Nullable;
28
29
30
31
32
33
34 @SuppressWarnings("serial")
35 public abstract class ImmutableCollection<E> extends AbstractCollection<E>
36 implements Serializable {
37
38 static final ImmutableCollection<Object> EMPTY_IMMUTABLE_COLLECTION
39 = new ForwardingImmutableCollection<Object>(Collections.emptyList());
40
41 ImmutableCollection() {}
42
43 public abstract UnmodifiableIterator<E> iterator();
44
45 public boolean contains(@Nullable Object object) {
46 return object != null && super.contains(object);
47 }
48
49 public final boolean add(E e) {
50 throw new UnsupportedOperationException();
51 }
52
53 public final boolean remove(Object object) {
54 throw new UnsupportedOperationException();
55 }
56
57 public final boolean addAll(Collection<? extends E> newElements) {
58 throw new UnsupportedOperationException();
59 }
60
61 public final boolean removeAll(Collection<?> oldElements) {
62 throw new UnsupportedOperationException();
63 }
64
65 public final boolean retainAll(Collection<?> elementsToKeep) {
66 throw new UnsupportedOperationException();
67 }
68
69 public final void clear() {
70 throw new UnsupportedOperationException();
71 }
72
73 private transient ImmutableList<E> asList;
74
75 public ImmutableList<E> asList() {
76 ImmutableList<E> list = asList;
77 return (list == null) ? (asList = createAsList()) : list;
78 }
79
80 ImmutableList<E> createAsList() {
81 switch (size()) {
82 case 0:
83 return ImmutableList.of();
84 case 1:
85 return ImmutableList.of(iterator().next());
86 default:
87 return new RegularImmutableAsList<E>(this, toArray());
88 }
89 }
90 static <E> ImmutableCollection<E> unsafeDelegate(Collection<E> delegate) {
91 return new ForwardingImmutableCollection<E>(delegate);
92 }
93
94 boolean isPartialView() {
95 return false;
96 }
97
98
99
100
101 public abstract static class Builder<E> {
102
103 Builder() {}
104
105 public abstract Builder<E> add(E element);
106
107 public Builder<E> add(E... elements) {
108 checkNotNull(elements);
109 for (E element : elements) {
110 add(checkNotNull(element));
111 }
112 return this;
113 }
114
115 public Builder<E> addAll(Iterable<? extends E> elements) {
116 checkNotNull(elements);
117 for (E element : elements) {
118 add(checkNotNull(element));
119 }
120 return this;
121 }
122
123 public Builder<E> addAll(Iterator<? extends E> elements) {
124 checkNotNull(elements);
125 while (elements.hasNext()) {
126 add(checkNotNull(elements.next()));
127 }
128 return this;
129 }
130
131 public abstract ImmutableCollection<E> build();
132 }
133 }